import { GameMode, world } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { GameComponent } from "@sapi-game/main";
import { Vector3Utils } from "@sapi-game/utils";
import { ElevatorCatPlayer } from "@/elevatorCat/player";
import { eleCatchState } from "../state";

export class ElevatorBellComponent extends GameComponent<eleCatchState> {
    override onAttach(): void {
        this.subscribe(world.afterEvents.playerInteractWithBlock, (t) => {
            if (
                !Vector3Utils.isEqual(t.block.location, this.context.bellPos) ||
                t.block.typeId != "minecraft:bell"
            ) {
                return;
            }
            const player = this.context.mouse.getById(t.player.id);
            if (player && !player.bell) {
                this.handlePlayerBell(player);
            }
        });
    }

    handlePlayerBell(player: ElevatorCatPlayer) {
        //没到时间不能盗铃
        const timer = this.state.getComponent(Timer);
        if (timer.time > this.context.config.time - 10 && timer.time > 30) {
            player.title(
                `${timer.time - this.context.config.time + 10}s后可盗铃`
            );
            return;
        }
        player.bell = true;
        player.player?.setGameMode(GameMode.Spectator);
        this.context.group.sendMessage(`§e${player.name} §r盗铃成功`);
    }
}
